package cn.angis.system.service;

import cn.angis.db.service.BaseService;
import cn.angis.system.mapper.RoleresMapper;
import cn.angis.system.model.Roleres;
import cn.hutool.core.collection.CollUtil;
import org.beetl.sql.core.SQLReady;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.noear.solon.data.annotation.Tran;

import java.util.ArrayList;
import java.util.List;

/**
* 角色和资源关联表服务
* @author angis.cn
* @Date 2023-01-05
*/
@ProxyComponent
public class RoleresService extends BaseService<RoleresMapper, Roleres> {

    @Inject
    private RoleService roleService;
    @Inject
    private ResourceService resourceService;
    @Inject
    private UserService userService;
    
    /**
     * 根据用户id获取角色key和资源权限列表
     * @param userId
     * @return: List<String>
     * @throws: 
     * @Date: 2023/1/8     
     */
    public List<String> getRoleAndResourceByUserId(String userId) {
        // 查询权限
        List<String> resourcesCodeList = resourceService.selectResourcesCodeByUserId(userId);
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(userId);
        CollUtil.addAll(resourcesCodeList, roleKeyList);
        return resourcesCodeList;
    }

    @Tran
    public int deleteByRoleId(String roleId) {
        return baseMapper.getSQLManager().executeUpdate(new SQLReady("delete from sys_role_res where role_id=?", roleId));
    }

    @Tran
    public void saveRoleRes(String userId, String roleId, List<String> resIds) {
        if (CollUtil.isNotEmpty(resIds)) {
            this.deleteByRoleId(roleId);
            List<Roleres> roleresList = new ArrayList<>();
            resIds.forEach(resId -> roleresList.add(new Roleres(roleId, resId)));
            this.saveBatch(roleresList);
            userService.refreshUserByUserId(userId);
        }
    }
}